package api

import (
	"gitee/com.xiaoxin/go-send/model"
	"gitee/com.xiaoxin/go-send/service"
	"github.com/gin-gonic/gin"
	"strconv"
)

type Controller struct {
	service service.ApiService
}

func NewController() *Controller {
	c := &Controller{
		service: service.NewApiService(),
	}
	return c
}

func (controller *Controller) RegisterRoute(g *gin.RouterGroup) {
	group := g.Group("tree")
	group.GET("/list", controller.treeList)
	group.POST("/directory", controller.saveOrUpdateDirectory)
	group.POST("/instance", controller.saveOrUpdateInstance)
	group.DELETE("/directory/:id", controller.deleteDirectory)
	group.DELETE("/instance/:id", controller.deleteInstance)
}

func (controller *Controller) treeList(c *gin.Context) {
	resp := model.SuccessResponse(controller.service.TreeList())
	c.JSON(200, resp)
}

func (controller *Controller) saveOrUpdateInstance(c *gin.Context) {
	var api *ApiVo = &ApiVo{}
	if err := c.ShouldBindJSON(api); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	var entity *model.Api = &model.Api{}
	entity.Name = api.Name
	entity.RequestInfo = api.RequestInfo
	id, err := strconv.Atoi(api.Id.String())
	if err != nil {
		id = 0
	}
	entity.Id = id
	directoryId, err := strconv.Atoi(api.DirectoryId.String())
	if err != nil {
		directoryId = 0
	}
	entity.DirectoryId = directoryId
	controller.service.SaveOrUpdateInstance(*entity)
	c.JSON(200, model.SuccessResponse(nil))
}

func (controller *Controller) saveOrUpdateDirectory(c *gin.Context) {
	var directory *ApiDirectoryVo = &ApiDirectoryVo{}
	if err := c.ShouldBindJSON(directory); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	var entity *model.ApiDirectory = &model.ApiDirectory{}
	entity.Name = directory.Name
	entity.Parents = directory.Parents
	id, err := strconv.Atoi(directory.Id.String())
	if err != nil {
		id = 0
	}
	entity.Id = id
	parentId, err := strconv.Atoi(directory.ParentId.String())
	if err != nil {
		parentId = 0
	}
	entity.ParentId = parentId

	if entity.Id == 1 {
		c.JSON(500, model.FailResponseDesc("root directory not permit change"))
		return
	}
	controller.service.SaveOrUpdateDirectory(*entity)
	c.JSON(200, model.SuccessResponse(nil))
}

func (controller *Controller) deleteDirectory(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	controller.service.DeleteDirectory(id)
	c.JSON(200, model.SuccessResponse(nil))
}

func (controller *Controller) deleteInstance(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	controller.service.DeleteInstance(id)
	c.JSON(200, model.SuccessResponse(nil))
}
